package com.guoyh.bilui.bottombar

import android.content.Context
import kotlin.jvm.JvmOverloads
import android.widget.LinearLayout
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.guoyh.baseutils.mylog.Loger
import com.guoyh.bilui.utils.UIUtils
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import android.util.AttributeSet
import android.view.View
import com.guoyh.bilui.R
import java.lang.IllegalArgumentException
import java.util.ArrayList

/**
 * @author ChayChan
 * @description: 底部页签根节点
 * @date 2017/6/23  11:02
 */
class BottomBarLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), ViewPager.OnPageChangeListener {
    private var mViewPager: ViewPager? = null
    private var mViewPager2: ViewPager2? = null
    private val mItemViews: MutableList<BottomBarItem> = ArrayList()
    private var mCurrentItem //当前条目的索引
            = 0
    private var mSmoothScroll: Boolean
    private var positon = 0
    private var iconHlColors = 0
    private var iconDfColors = 0
    private var textHlColor = 0
    private var textDfColor = 0
    override fun onFinishInflate() {
        super.onFinishInflate()
        init()
    }

    override fun setOrientation(orientation: Int) {
        super.setOrientation(orientation)
    }

    fun setViewPager(viewPager: ViewPager?) {
        mViewPager = viewPager
        if (mViewPager != null && mViewPager2 != null) {
            val adapter = mViewPager!!.adapter
            require(!(adapter != null && adapter.count != childCount)) { "LinearLayout的子View数量必须和ViewPager条目数量一致" }
        }
        if (mViewPager != null && mViewPager2 != null) {
            mViewPager!!.setOnPageChangeListener(this)
        }
    }

    private fun init() {
        mItemViews.clear()
        val childCount = childCount
        if (childCount == 0) {
            return
        }
        for (i in 0 until childCount) {
            if (getChildAt(i) is BottomBarItem) {
                val bottomBarItem = getChildAt(i) as BottomBarItem
                mItemViews.add(bottomBarItem)
                //设置点击监听
                bottomBarItem.setOnClickListener(MyOnClickListener(i))
            } else {
                throw IllegalArgumentException("BottomBarLayout的子View必须是BottomBarItem")
            }
        }
        if (mCurrentItem < mItemViews.size) {
            Loger.dd("============")
            mItemViews[mCurrentItem].refreshTab(true)
        }
    }

    fun addItem(item: BottomBarItem) {
        val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
        layoutParams.weight = 1f
        item.layoutParams = layoutParams
        addView(item)
        init()
    }

    fun removeItem(position: Int) {
        if (position >= 0 && position < mItemViews.size) {
            val item = mItemViews[position]
            if (mItemViews.contains(item)) {
                resetState()
                removeViewAt(position)
                init()
            }
        }
    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
    override fun onPageSelected(position: Int) {
        selVpPos(position)
    }

    override fun onPageScrollStateChanged(state: Int) {}

    fun setParams(
        positon: Int,
        iconHlColors: Int,
        iconDfColors: Int,
        textHlColor: Int,
        textDfColor: Int
    ) {
        this.positon = positon
        this.iconHlColors = iconHlColors
        this.iconDfColors = iconDfColors
        this.textHlColor = textHlColor
        this.textDfColor = textDfColor
        toSetSelColor()
    }

    private fun toSetSelColor() {
        val childCount = childCount
        Loger.dd("Layout 进入,", childCount)
        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            Loger.dd("=========", childView)
            if (childView is BottomBarItem) {
                val img = childView.imageView
                val text = childView.textView
                Loger.dd(text.text.toString() + "=========" + childView.isSelected())
                //
                childView.setColor(textHlColor, textDfColor, iconHlColors, iconDfColors)

//
                UIUtils.setImageViewColor(
                    img,
                    if (childView.isSelected()) iconHlColors else iconDfColors
                )
                text.setTextColor(if (childView.isSelected()) textHlColor else textDfColor)
                //
            }
            //            else
//            {
//                Loger.dd("====类型不符");
//            }
        }
        Loger.dd(mItemViews.size)
    }

    private inner class MyOnClickListener(private val currentIndex: Int) : OnClickListener {
        override fun onClick(v: View) {


            //回调点击的位置
            if (mViewPager != null && mViewPager2 != null) {
                //有设置viewPager
                if (currentIndex == mCurrentItem) {
                    //如果还是同个页签，使用setCurrentItem不会回调OnPageSelecte(),所以在此处需要回调点击监听
                    if (onItemSelectedListener != null) {
                        onItemSelectedListener!!.onItemSelected(
                            getBottomItem(currentIndex),
                            mCurrentItem,
                            currentIndex
                        )
                    }
                } else {
                    mViewPager!!.setCurrentItem(currentIndex, mSmoothScroll)
                }
            } else {
                Loger.dd("======")
                updateTabState(currentIndex)
                //没有设置viewPager
                if (onItemSelectedListener != null) {
                    onItemSelectedListener!!.onItemSelected(
                        getBottomItem(currentIndex),
                        mCurrentItem,
                        currentIndex
                    )
                }
            }
        }
    }

    private fun updateTabState(position: Int) {
        Loger.dd("============", position)
        resetState()
        mCurrentItem = position
        mItemViews[mCurrentItem].refreshTab(true)
    }

    /**
     * 重置当前按钮的状态
     */
    private fun resetState() {
        Loger.dd("============")
        if (mCurrentItem < mItemViews.size) {
            if (mItemViews[mCurrentItem].isSelected) {
                mItemViews[mCurrentItem].refreshTab(false)
            }
        }
    }

    /**
     * 选哪个  vp跟着滑动
     */
    fun setCurrentItemWithVp(currentItem: Int) {
        if (mViewPager != null && mViewPager2 != null) {
            mViewPager!!.setCurrentItem(currentItem, mSmoothScroll)
        } else {
            if (onItemSelectedListener != null) {
                onItemSelectedListener!!.onItemSelected(
                    getBottomItem(currentItem),
                    mCurrentItem,
                    currentItem
                )
            }
            updateTabState(currentItem)
        }
    }

    /**
     * 设置未读数
     *
     * @param position  底部标签的下标
     * @param unreadNum 未读数
     */
    fun setUnread(position: Int, unreadNum: Int) {
        mItemViews[position].setUnreadNum(unreadNum)
    }

    /**
     * 设置提示消息
     *
     * @param position 底部标签的下标
     * @param msg      未读数
     */
    fun setMsg(position: Int, msg: String?) {
        mItemViews[position].setMsg(msg)
    }

    /**
     * 隐藏提示消息
     *
     * @param position 底部标签的下标
     */
    fun hideMsg(position: Int) {
        mItemViews[position].hideMsg()
    }

    /**
     * 显示提示的小红点
     *
     * @param position 底部标签的下标
     */
    fun showNotify(position: Int) {
        mItemViews[position].showNotify()
    }

    /**
     * 隐藏提示的小红点
     *
     * @param position 底部标签的下标
     */
    fun hideNotify(position: Int) {
        mItemViews[position].hideNotify()
    }

    /**
     * 只更新底部状态 不管vp
     */
    var currentItem: Int
        get() = mCurrentItem
        set(currentItem) {
            if (onItemSelectedListener != null) {
                onItemSelectedListener!!.onItemSelected(
                    getBottomItem(currentItem),
                    mCurrentItem,
                    currentItem
                )
            }
            updateTabState(currentItem)
        }

    fun setSmoothScroll(smoothScroll: Boolean) {
        mSmoothScroll = smoothScroll
    }

    fun getBottomItem(position: Int): BottomBarItem {
        return mItemViews[position]
    }

    private var onItemSelectedListener: OnItemSelectedListener? = null

    interface OnItemSelectedListener {
        fun onItemSelected(
            bottomBarItem: BottomBarItem?,
            previousPosition: Int,
            currentPosition: Int
        )
    }

    fun setOnItemSelectedListener(onItemSelectedListener: OnItemSelectedListener?) {
        this.onItemSelectedListener = onItemSelectedListener
    }

    fun setViewPager2(viewPager: ViewPager2) {
        mViewPager2 = viewPager
        viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                selVpPos(position)
            }
        })
    }

    private fun selVpPos(position: Int) {
        resetState()
        mItemViews[position].refreshTab(true)

//        if (onItemSelectedListener != null) {
//            onItemSelectedListener.onItemSelected(getBottomItem(position), mCurrentItem, position);
//        }
        mCurrentItem = position //记录当前位置
    }

    init {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.BottomBarLayout)
        mSmoothScroll = ta.getBoolean(R.styleable.BottomBarLayout_smoothScroll, false)
        ta.recycle()
    }
}